package com.tuozixuan;

import java.io.File;
import java.io.IOException;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import static com.tuozixuan.GitDemoConstants.*;

/**
 * 本地已存在目录初始化为仓库后推送到远程
 * 
 * <pre>
 * cd "/Users/zhimaxingzhe/test"
 * git init
 * git remote add origin https://github.com/zhimaxingzhe/test.git
 * git add .
 * git commit -m "init"
 * git push -u origin master
 * </pre>
 */
public class GitInitDemo {

	public static void main(String[] args) throws IllegalStateException, GitAPIException, IOException {
		
		Git git = Git.init().setDirectory(new File(LOCAL_DIR)).call();
		StoredConfig storedConfig = git.getRepository().getConfig();
		storedConfig.setString("remote", "origin", "url", GIT_URL);
		storedConfig.save();
		git.commit().setMessage("init").call();
		
		UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(USERNAME, PASSWORD);
		git.push().setRemote("origin").setCredentialsProvider(provider).setRefSpecs(new RefSpec(BRANCH_NAME)).call();
	}

}
